package com.next

import grails.converters.JSON
import grails.gorm.transactions.Transactional
import groovy.json.JsonOutput
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import groovyx.net.http.ContentType
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method

@Transactional
@CompileStatic
@TypeChecked
class PropertyValuationProviderService
{
    String key = "FC3260DDC8A11A0488007519EDE1A09A"
    // String key = "6A084092CB5B49C1E0534C0AA8C0CDA7"
    String apiUrl = "http://a27.cindata.cn/"
    // String key = "62064F070D70A52DE0532901C90A9662"
    // String apiUrl = "http://192.168.10.30/"
    String key1 = "3963c3b2252d494eb231240e3df6e282"
    String evaluateApiUrl = "http://192.168.10.73:8088/api4kuaidai/"

    def evaluate(params)
    {
        String cityName = params['city']

        City city = City.find("from City where name = ?",[cityName])
        if (!city)
        {
            return 0
        }

        def provider = CityPropertyValuationProvider.find("from CityPropertyValuationProvider where city.id = ?",[city?.id]).provider

        if (!provider)
        {
            provider = PropertyValuationProvider.find("from PropertyValuationProvider where code = 'FGG'")
        }
        String cityEncoder = URLEncoder.encode(city.name, "UTF-8")
        def urlString = "${provider.apiUrl}?city=${cityEncoder}"

        println urlString

        def url = new URL(urlString)
        def connection = (HttpURLConnection) url.openConnection()
        connection.setDoOutput(true)
        connection.setRequestMethod("GET")
        println connection.getConnectTimeout()
        println connection.getResponseCode()
        if (connection.getResponseCode() == 200)
        {
            def result = connection.inputStream.withReader { Reader reader -> reader.text }
            def json = JSON.parse(result)
            println json
            return json
        } else
        {
            return 0
        }
    }

    def appQueryPrice(House house)
    {
        println "##############appQueryPrice service start:" + new Date() + "########"
        def result = 0
        def params = [:]
        params['em'] = "1"
        params['city'] = house?.city?.name
        params['district'] = house?.district
        params['name'] = house?.projectName
        params['buildingName'] = house?.building
        params['floor'] = house?.floor
        params['totalfloor'] = house?.totalFloor
        params['square'] = house?.area
        params['aspect'] = house?.orientation
        params['fitment'] = house?.decoration
        params = params as JSON
        try
        {
            // def urlString = apiUrl + "api/evaluate.do?key=" + key
            String urlString = apiUrl + "api/evaluate?key=" + key
            println urlString
            def url = new URL(urlString)
            HttpURLConnection connection = (HttpURLConnection) url.openConnection()
            connection.setDoOutput(true)
            connection.setRequestMethod("POST")
            connection.setRequestProperty("Content-Type", "application/json")
            connection.outputStream.withWriter("UTF-8") { Writer writer -> writer.write params.toString() }
            println connection.getResponseCode()
            if (connection.getResponseCode() == 200)
            {
                def results = connection.inputStream.withReader("UTF-8") { Reader reader -> reader.text }
                if (results)
                {
                    def json = JSON.parse(results)
                    result = json
                }
            }
        }
        catch (Exception e)
        {
            println e
        }
        finally
        {
            println "appQueryPrice result:" + result
            return result
        }
    }

    //極速詢值接口
    def appQueryPrice1(House house, String pictUrl)
    {
        println "##############appQueryPrice1 service start:" + new Date() + "########"
        def result = 0
        def params = [:]
        params['em'] = "5"
        params['city'] = house?.city?.name
        params['name'] = house?.projectName
        params['pictUrl'] = pictUrl
        params = params as JSON
        try
        {
            // def urlString = evaluateApiUrl + "api/evaluate.do?key=" + key1
            String urlString = apiUrl + "api/evaluate?key=" + key
            println urlString
            def url = new URL(urlString)
            HttpURLConnection connection = (HttpURLConnection) url.openConnection()
            connection.setDoOutput(true)
            connection.setRequestMethod("POST")
            connection.setRequestProperty("Content-Type", "application/json")
            connection.outputStream.withWriter("UTF-8") { Writer writer -> writer.write params.toString() }
            println connection.getResponseCode()
            if (connection.getResponseCode() == 200)
            {
                def results = connection.inputStream.withReader("UTF-8") { Reader reader -> reader.text }
                if (results)
                {
                    def json = JSON.parse(results)
                    result = json
                }
            }
        }
        catch (Exception e)
        {
            println e
        }
        finally
        {
            println "appQueryPrice1 result:" + result
            return result
        }
    }

    def queryPrice(House house)
    {
        println "##############估值service开始:" + new Date() + "########3"
        def params = [:]
        params['em'] = "1"
        params['city'] = house.city.name
        //行政区
        params['district'] = house.district
        params['projectName'] = house.projectName
        params['building'] = house.building
        if (house.unit)
        {
            params['unit'] = house.unit
        } else
        {
            params['unit'] = "0"
        }
        params['floor'] = house.floor
        params['roomNumber'] = house.roomNumber
        params['totalFloor'] = house.totalFloor
        params['area'] = house.area
        params['address'] = house.address
        params['orientation'] = house.orientation
        params['houseType'] = house.houseType
        params['assetType'] = house.assetType
        println house.specialFactors
        if (house.specialFactors != "无")
        {
            params['specialFactors'] = house.specialFactors
        }
        if (house.appliedTotalPrice)
        {
            params['appliedTotalPrice'] = house.appliedTotalPrice
        } else
        {
            params['appliedTotalPrice'] = 0
        }
        params['atticArea'] = house.atticArea
        println "估值参数："
        println params
        def paramsJson = JsonOutput.toJson(params)
        String urlString = apiUrl + "api/evaluate.do?key=" + key
        def url = new URL(urlString)
        HttpURLConnection connection = (HttpURLConnection) url.openConnection()
        connection.setDoOutput(true)
        connection.setRequestMethod("POST")
        connection.setRequestProperty("Content-Type", "application/json")
        connection.outputStream.withWriter { Writer writer -> writer.write paramsJson }
        println connection.getResponseCode()
        if (connection.getResponseCode() == 200)
        {
            def result = connection.inputStream.withReader { Reader reader -> reader.text }
            println "估计结果：" + result
            if (!result)
            {
                println "##############估值service结束:" + new Date() + "########3"
                println "######返回为空####"
                return 0
            } else
            {
                def json = JSON.parse(result)
                println "##############估值service结束:" + new Date() + "########3"
                return json
            }
        } else
        {
            println "估值失败"
            println "##############估值service结束:" + new Date() + "########3"
            return 0
        }
    }

    /**
     * Created by 任晓文
     * app询值接口--世联
     * */
    def queryPrice2(House house)
    {
        println "##############估值service开始:" + new Date() + "########3"
        def params = [:]
        params['city'] = house.city.name
        params['district'] = house.district
        params['projectName'] = house.projectName
        params['building'] = house.building
        if (house.unit)
        {
            params['unit'] = house.unit
        } else
        {
            params['unit'] = "0"
        }
        // params['unit'] =house.unit
        params['floor'] = house.floor
        params['roomNumber'] = house.roomNumber
        params['totalFloor'] = house.totalFloor
        params['area'] = house.area
        params['address'] = house.address
        params['orientation'] = house.orientation
        params['houseType'] = house.houseType
        params['assetType'] = house.assetType
        println house.specialFactors
        if (house.specialFactors != "无")
        {
            params['specialFactors'] = house.specialFactors
        }
        if (house.appliedTotalPrice)
        {
            params['appliedTotalPrice'] = house.appliedTotalPrice
        } else
        {
            params['appliedTotalPrice'] = 0
        }
        params['atticArea'] = house.atticArea
        //add opportunitySerialNumber
        params['opportunity'] = house?.opportunity?.serialNumber
        println "估值参数："
        println params
        def paramsJson = JsonOutput.toJson(params)

        def urlString = CreditReportProvider.find("from CreditReportProvider where code = 'PV'")?.apiUrl + "/provider/evaluate2"
        def url = new URL(urlString)
        HttpURLConnection connection = (HttpURLConnection) url.openConnection()
        connection.setDoOutput(true)
        connection.setRequestMethod("GET")
        connection.setRequestProperty("Content-Type", "application/json")
        connection.outputStream.withWriter { Writer writer -> writer.write paramsJson }
        println connection.getResponseCode()
        if (connection.getResponseCode() == 200)
        {
            def result = connection.inputStream.withReader { Reader reader -> reader.text }
            println "估计结果：" + result
            if (!result)
            {
                println "##############估值service结束:" + new Date() + "########3"
                println "######返回为空####"
                return 0
            } else
            {
                def json = JSON.parse(result)
                println "##############估值service结束:" + new Date() + "########3"
                return json
            }
        } else
        {
            println "估值失败"
            println "##############估值service结束:" + new Date() + "########3"
            return 0
        }
    }

    def searchProjectName(String city, String district, String projectName)
    {
        println "searchProjectName start"

        def result = 0
        def params = [:]
        params['cityCode'] = city
        params['districtCode'] = district
        params['name'] = projectName
        params['limit'] = 10
        params = params as JSON
        try
        {
            // def urlString = apiUrl + "api/getCommunityByDistrictService.do?key=" + key
            String urlString = apiUrl + "api/getCommunityByDistrictService?key=" + key
            println urlString
            def url = new URL(urlString)
            HttpURLConnection connection = (HttpURLConnection) url.openConnection()
            connection.setDoOutput(true)
            connection.setRequestMethod("POST")
            connection.setUseCaches(false)
            connection.setRequestProperty("Content-Type", "application/json")

            connection.outputStream.withWriter("UTF-8") { Writer writer -> writer.write params.toString() }
            println connection.getResponseCode()

            if (connection.getResponseCode() == 200)
            {
                def results = connection.inputStream.withReader("UTF-8") { Reader reader -> reader.text }
                result = JSON.parse(results)
            }
        }
        catch (Exception e)
        {
            println e
        }
        finally
        {
            // println "searchProjectName result:"+result
            return result
        }
    }

    def searchBuilding(String cityCode, String communityId, String buildingName = "")
    {
        println "searchBuilding start"

        def result = 0
        def params = [:]
        params['cityCode'] = cityCode
        params['communityId'] = communityId
        params['buildingName'] = buildingName
        params = params as JSON
        try
        {
            // def urlString = apiUrl + "api/getCommunityByDistrictService.do?key=" + key
            String urlString = apiUrl + "api/getBuildingByCommunityService?key=" + key
            println urlString
            def url = new URL(urlString)
            HttpURLConnection connection = (HttpURLConnection) url.openConnection()
            connection.setDoOutput(true)
            connection.setRequestMethod("POST")
            connection.setUseCaches(false)
            connection.setRequestProperty("Content-Type", "application/json")

            connection.outputStream.withWriter("UTF-8") { Writer writer -> writer.write params.toString() }
            println connection.getResponseCode()

            if (connection.getResponseCode() == 200)
            {
                def results = connection.inputStream.withReader("UTF-8") { Reader reader -> reader.text }
                result = JSON.parse(results)
            }
        }
        catch (Exception e)
        {
            println e
        }
        finally
        {
            // println "searchProjectName result:"+result
            return result
        }
    }

    def searchUnit(String cityCode, String communityId, String buildingId, String unitName = "")
    {
        println "searchUnit start"

        def result = 0
        def params = [:]
        params['cityCode'] = cityCode
        params['communityId'] = communityId
        params['buildingId'] = buildingId
        params['unitName'] = unitName
        params = params as JSON
        try
        {
            // def urlString = apiUrl + "api/getCommunityByDistrictService.do?key=" + key
            String urlString = apiUrl + "api/getunitByBuildingService?key=" + key
            println urlString
            def url = new URL(urlString)
            HttpURLConnection connection = (HttpURLConnection) url.openConnection()
            connection.setDoOutput(true)
            connection.setRequestMethod("POST")
            connection.setUseCaches(false)
            connection.setRequestProperty("Content-Type", "application/json")

            connection.outputStream.withWriter("UTF-8") { Writer writer -> writer.write params.toString() }
            println connection.getResponseCode()

            if (connection.getResponseCode() == 200)
            {
                def results = connection.inputStream.withReader("UTF-8") { Reader reader -> reader.text }
                result = JSON.parse(results)
            }
        }
        catch (Exception e)
        {
            println e
        }
        finally
        {
            // println "searchProjectName result:"+result
            return result
        }
    }

    def searchHouse(String cityCode, String buildingId, String unitId, String house = "")
    {
        println "searchHouse start"

        def result = 0
        def params = [:]
        params['cityCode'] = cityCode
        params['buildingId'] = buildingId
        params['unitId'] = unitId
        params['house'] = house
        params = params as JSON
        try
        {
            // def urlString = apiUrl + "api/getCommunityByDistrictService.do?key=" + key
            String urlString = apiUrl + "api/getHouseByUnitService?key=" + key
            println urlString
            def url = new URL(urlString)
            HttpURLConnection connection = (HttpURLConnection) url.openConnection()
            connection.setDoOutput(true)
            connection.setRequestMethod("POST")
            connection.setUseCaches(false)
            connection.setRequestProperty("Content-Type", "application/json")

            connection.outputStream.withWriter("UTF-8") { Writer writer -> writer.write params.toString() }
            println connection.getResponseCode()

            if (connection.getResponseCode() == 200)
            {
                def results = connection.inputStream.withReader("UTF-8") { Reader reader -> reader.text }
                result = JSON.parse(results)
            }
        }
        catch (Exception e)
        {
            println e
        }
        finally
        {
            // println "searchProjectName result:"+result
            return result
        }
    }

    def suggestSubmmit(def suggest)
    {
        println suggest
        println "##############估值反馈suggestSubmmit开始########3"
        String param = JsonOutput.toJson(suggest)
        println param
        def urlString = CreditReportProvider.find("from CreditReportProvider where code = 'PV'")?.apiUrl + "/provider/applicationPriceAdjustment"
        def url = new URL(urlString)
        HttpURLConnection connection = (HttpURLConnection) url.openConnection()
        connection.setDoOutput(true)
        connection.setRequestMethod("GET")
        connection.setRequestProperty("Content-Type", "application/json")
        connection.outputStream.withWriter { Writer writer -> writer.write param }
        println connection.getResponseCode()
        if (connection.getResponseCode() == 200)
        {
            def result = connection.inputStream.withReader { Reader reader -> reader.text }
            def json = JSON.parse(result)
            println "#######true#######估值反馈suggestSubmmit结束########3"
            println json
            return json
        } else
        {
            println "######false########估值反馈suggestSubmmit结束########3"
            return ""
        }
    }

    def suggestSubmmit1(String param)
    {
        println "##############估值反馈suggestSubmmit开始########3"
        println param
        String urlString = CreditReportProvider.find("from CreditReportProvider where code = 'PV'")?.apiUrl + "/provider/applicationPriceAdjustment"
        def url = new URL(urlString)
        HttpURLConnection connection = (HttpURLConnection) url.openConnection()
        connection.setDoOutput(true)
        connection.setRequestMethod("GET")
        connection.setRequestProperty("Content-Type", "application/json")
        connection.outputStream.withWriter { Writer writer -> writer.write param }
        println connection.getResponseCode()
        if (connection.getResponseCode() == 200)
        {
            def result = connection.inputStream.withReader { Reader reader -> reader.text }
            def json = JSON.parse(result)
            println "#######true#######估值反馈suggestSubmmit结束########3"
            println json
            return json
        } else
        {
            println "######false########估值反馈suggestSubmmit结束########3"
            return ""
        }
    }

    def updateFastUnitPrice(String externalId, String fastUnitPrice)
    {
        println "################## updateFastUnitPrice start ###########################"
        def params = "externalId=${externalId}&fastSellPrice=${fastUnitPrice}"
        println params
        def map = [:]

        try
        {
            String urlString = CreditReportProvider.find("from CreditReportProvider where code = 'PV'")?.apiUrl + "/house/updateFastUnitPrice"
            def url = new URL(urlString)
            HttpURLConnection connection = (HttpURLConnection) url.openConnection()
            connection.setDoOutput(true)
            connection.setRequestMethod("POST")
            connection.outputStream.withWriter { Writer writer -> writer.write params }
            println connection.getResponseCode()
            if (connection.getResponseCode() == 200)
            {
                def result = connection.inputStream.withReader { Reader reader -> reader.text }
                def json = JSON.parse(result)
                def errorCode = json['errorCode']

                if ((errorCode == 4003) || (errorCode == 4004))
                {
                    map['flag'] = false
                    map['message'] = json['errorMessage']
                    return map
                } else
                {
                    map['flag'] = true
                    map['message'] = json['errorMessage']
                    return map
                }
            } else
            {
                println "house/updateFastUnitPrice interface error"

                map['flag'] = false
                map['message'] = "PV接口异常"
                return map
            }
        }
        catch (Exception e)
        {
            println "pv connection error: " + e

            map['flag'] = false
            map['message'] = "PV网络异常"
            return map
        }
    }

    def queryByExternalId(String externalId)
    {
        println "################## queryByExternalId start ###########################"
        // def params = "externalId=${externalId}"
        // def valuationReliability
        // def json
        // try
        // {
        //     def urlString = CreditReportProvider.find("from CreditReportProvider where code = 'PV'")?.apiUrl+"/provider/queryByExternalId"
        //     def url = new URL(urlString)
        //     HttpURLConnection connection = (HttpURLConnection) url.openConnection()
        //     connection.setDoOutput(true)
        //     connection.setRequestMethod("POST")
        //     connection.outputStream.withWriter("UTF-8") { Writer writer -> writer.write params }
        //     println connection.getResponseCode()
        //     if (connection.getResponseCode() == 200)
        //     {
        //         def result = connection.inputStream.withReader("UTF-8") { Reader reader -> reader.text }
        //         if (result)
        //         {
        //             json = JSON.parse(result)
        //             valuationReliability = json['valuationReliability']
        //         }
        //     }
        // }
        // catch (Exception e)
        // {
        //     println "pv connection error: " + e
        // }

        // return json

        return null
    }
}
